<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue'
import {
  searchAppAll,
  searchGroupTree,
  insertGroup,
  updateGroupById,
  selectGroupById
} from '@code/api/application'
import { resetFormPlus } from '@/utils/zmids'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getPinyin } from '@/api/common'

interface Form {
  groupCode: string
  groupName: string
  groupIndex: number
  groupParentId: string
  groupAppId: string
}

const queryParams = reactive({
  groupCodeLike: '',
  groupNameLike: '',
  orderBy: 'GROUP_APP_ID,GROUP_INDEX',
  sortDirect: 'ASC,ASC',
})

const showSearch = ref<Boolean>(true)

const showDialog = ref<Boolean>(false)

const title = ref<string>('')

const type = ref('add')

const form = ref<Form>({
  groupCode: '',
  groupName: '',
  groupIndex: 999,
  groupParentId: '',
  groupAppId: ''
})

const rules = {
  groupName: [{ required: true, message: '分组名称不能为空', trigger: 'blur' }],
  groupCode: [{ required: true, message: '分组编码不能为空', trigger: 'blur' }],
  groupIndex: [{ required: true, message: '分组顺序不能为空', trigger: 'blur' }],
}

const formRef = ref<FormInstance>()

const queryForm = ref<FormInstance>()

const appList = ref([])

const groupList = ref([])

const defaultProps = {
  label: 'codeAppName',
  children: 'children'
}

const tree = ref([])

const curGroupAppId = ref('')

const parentGroupId = ref('')

const initForm = () => {
  resetFormPlus(formRef.value)
  form.value = {
    groupCode: '',
    groupName: '',
    groupIndex: 999,
    groupParentId: '',
    groupAppId: ''
  }
}

const getAppList = async () => {
  return searchAppAll().then((res) => {
    appList.value = res.data
  })
}

const getGroupList = async () => {
  return searchGroupTree(curGroupAppId.value, queryParams).then((res) => {
    groupList.value = res.data
  })
}

const init = async () => {
  await getAppList()
  if (appList.value && appList.value.length) {
    curGroupAppId.value = appList.value[0].codeAppId
    getGroupList()
  }
}

const handleQuery = () => {
  getGroupList()
}

const resetQuery = () => {
  resetFormPlus(queryForm.value)
  handleQuery()
}

const handleNodeClick = (node) => {
  curGroupAppId.value = node.codeAppId
  getGroupList()
}

const handleAdd = (row?: any) => {
  if (row) {
    parentGroupId.value = row.groupId
  }
  initForm()
  type.value = 'add'
  title.value = '新增分组'
  showDialog.value = true
}

const handleUpdate = (row: any) => {
  selectGroupById(row.groupId).then((response) => {
    form.value = response.data
    type.value = 'update'
    title.value = '修改分组'
    showDialog.value = true
  })
}

const handleDelete = (row: any) => {
  const params = {
    ...row,
    isDelete: 'Y'
  }
  updateGroupById(params)
    .then((res) => {
      ElMessage.success('删除成功')
      getGroupList()
    })
    .catch(function () {})
}

const submitForm = (ref: FormInstance) => {
  if (!ref) {
    return
  }
  ref.validate((valid) => {
    if (valid) {
      if (type.value == 'update') {
        updateGroupById(form.value).then((response) => {
          if (response.data === 1) {
            ElMessage.success('修改成功')
            showDialog.value = false
            getGroupList()
          }
        })
      } else {
        const params = {
          ...form.value,
          groupAppId: curGroupAppId.value,
          groupParentId: parentGroupId.value
        }
        insertGroup(params).then((response) => {
          if (response.code === '200') {
            ElMessage.success('新增成功')
            showDialog.value = false
            getGroupList()
          }
        })
      }
    }
  })
}

const cancel = () => {
  showDialog.value = false
  initForm()
}

const chineseTrans = (value: string) => {
  nextTick(() => {
    if (value) {
      getPinyin(value).then((res) => {
        form.value.groupCode = res.data
      })
    } else {
      form.value.groupCode = ''
    }
  })
}

init()
</script>

<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <el-tree
          :data="appList"
          :props="defaultProps"
          :expand-on-click-node="false"
          ref="tree"
          default-expand-all
          highlight-current
          :default-checked-keys="[0]"
          @node-click="handleNodeClick"
        />
      </el-col>
      <el-col :span="20">
        <div>
          <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="分组编码" prop="groupCodeLike">
              <el-input
                v-model="queryParams.groupCodeLike"
                placeholder="请输入分组编码"
                clearable
                size="default"
                style="width: 240px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="分组名称" prop="groupNameLike">
              <el-input
                v-model="queryParams.groupNameLike"
                placeholder="请输入分组名称"
                clearable
                size="default"
                style="width: 240px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <search-button @click="handleQuery" />
              <reset-button @click="resetQuery" />
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <add-button @click="handleAdd" />
            <right-toolbar v-model:showSearch="showSearch" @query-table="getGroupList" />
          </el-row>
          <el-table :data="groupList" row-key="groupId">
            <el-table-column prop="groupName" label="分组名称" />
            <el-table-column prop="groupCode" label="分组编码" />
            <el-table-column prop="groupIndex" label="分组顺序" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" align="center" width="240">
              <template #default="scope">
                <text-add-button @click="handleAdd(scope.row)" />
                <text-edit-button @click="handleUpdate(scope.row)" />
                <text-delete-button
                  @click="handleDelete(scope.row)"
                  :title="'是否确认删除' + scope.row.groupName + '?'"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>

    <drag-dialog v-model="showDialog" :title="title">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入分组名称" @input="chineseTrans" />
        </el-form-item>
        <el-form-item label="分组编码" prop="groupCode">
          <el-input v-model="form.groupCode" placeholder="请输入分组编码" />
        </el-form-item>
        <el-form-item label="分组顺序" prop="groupIndex">
          <el-input v-model="form.groupIndex" placeholder="请输入分组顺序" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm(formRef)">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </drag-dialog>
  </div>
</template>
